﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChinaDynastyTours.Controls;
using ChinaDynastyTours.Helpers;
using IToursDataService.Models;

namespace ChinaDynastyTours.Views
{
    public partial class TrainOrderForm : DevExpress.XtraEditors.XtraForm
    {
        public string _TrainCode { get; set; }         //航班号
        public string _StartCity { get; set; }          //始发城市
        public string _EndCity { get; set; }            //到达城市
        public string _StartTime { get; set; }          //始发时间
        public string _EndTime { get; set; }            //结束时间

        TrainTimeWebService _trainTime = new TrainTimeWebService(WcfClient.UseService((IToursDataService.ISysParameterCtrl s) => (s.GetValueForKey("TrainTimeServiceURL"))));//SysParameterCtrl.GetValueForKey("TrainTimeServiceURL"));

        List<TrainEntity> _trains = new List<TrainEntity>();
        string _beginPosition, _endPosition;//用于在线查询时保存起始和终止地址
        
        public TrainOrderForm()
        {
            InitializeComponent();
        }

        private void TrainOrderForm_Load(object sender, EventArgs e)
        {
            tbBeginPosition.EditValue = _StartCity;
            tbEndPosition.EditValue = _EndCity;
            tbBeginPosition1.EditValue = _StartCity;
            tbEndPosition1.EditValue = _EndCity;

            _trainTime.getStationAndTimeByStationNameCompleted += new getStationAndTimeByStationNameCompletedEventHandler(GetStationAndTimeByStationNameCompleted);
            btnRefresh.PerformClick();

        }
        void GetStationAndTimeByStationNameCompleted(object sender, getStationAndTimeByStationNameCompletedEventArgs e)
        {
            DevExpress.Utils.ToolTipController tip = ApplicationHelper.ShowLoadTip("从互联网加载数据...", trainGridControl1);

            try
            {
                if (e.Error != null)
                {
                    MessageBox.Show("查询错误：" + e.Error, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (e.Result.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("查无数据", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                _trains.Clear();
                foreach (DataRow dr in e.Result.Tables[0].Rows)
                    _trains.Add(new TrainEntity { TrainCode = dr["TrainCode"].ToString(), BeginPosition = dr["StartStation"].ToString(), EndPosition = dr["ArriveStation"].ToString(), StartTime = dr["StartTime"].ToString(), EndTime = dr["ArriveTime"].ToString() });
                
                trainGridControl1.DataSource = _trains;
                trainGridView1.RefreshData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询错误：" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally {
                btnRefresh1.Enabled = true;
                ProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                ProgressBarEdit.Stopped = true;
                lblProgress.Caption = "完毕";
                tip.HideHint();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (sender.Equals(btnRefresh))
            {
                if (tbBeginPosition.Text.Trim() == "" && tbEndPosition.Text.Trim() == "") return;
                
                string beginPositionPy = CN2PYHelper.CapitalCovert(tbBeginPosition.Text);
                string endPositionPy = CN2PYHelper.CapitalCovert(tbEndPosition.Text);

                trainGridControl.DataSource = WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.GetTrainData(beginPositionPy, endPositionPy))); //BaseInfoCtrl.GetTrainData(beginPositionPy, endPositionPy);
            }
            else
            {
                if (tbBeginPosition1.Text == "" || tbEndPosition1.Text == "")
                {
                    MessageBox.Show("‘出发站’和‘到达站’必须填写！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    return;
                }
                //保存变量
                _beginPosition = tbBeginPosition1.Text;
                _endPosition = tbEndPosition1.Text;

                btnRefresh1.Enabled = false;
                ProgressBar.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                ProgressBarEdit.Stopped = false;
                lblProgress.Caption = "正在检索...";
                _trainTime.getStationAndTimeByStationNameAsync(tbBeginPosition1.Text, tbEndPosition1.Text, "");
            }
        }

        private void trainGridView_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (e.Clicks == 2)//双击
                if (sender.Equals(trainGridView))
                    btnOK.PerformClick();
                else
                    btnOK1.PerformClick();
        }
        
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (sender.Equals(btnOK))
            {
                if (trainGridView.FocusedRowHandle < 0) return;

                _TrainCode = trainGridView.GetDataRow(trainGridView.FocusedRowHandle)["TrainCode"].ToString();
                _StartCity = trainGridView.GetDataRow(trainGridView.FocusedRowHandle)["BeginPosition"].ToString();
                _EndCity = trainGridView.GetDataRow(trainGridView.FocusedRowHandle)["EndPosition"].ToString();
                _StartTime = trainGridView.GetDataRow(trainGridView.FocusedRowHandle)["StartTime"].ToString();
                _EndTime = trainGridView.GetDataRow(trainGridView.FocusedRowHandle)["EndTime"].ToString();
            }
            else
            {
                if (trainGridView1.FocusedRowHandle < 0) return;

                _TrainCode = trainGridView1.GetRowCellValue(trainGridView1.FocusedRowHandle,"TrainCode").ToString();
                _StartCity = trainGridView1.GetRowCellValue(trainGridView1.FocusedRowHandle, "BeginPosition").ToString();
                _EndCity = trainGridView1.GetRowCellValue(trainGridView1.FocusedRowHandle, "EndPosition").ToString();
                _StartTime = trainGridView1.GetRowCellValue(trainGridView1.FocusedRowHandle, "StartTime").ToString();
                _EndTime = trainGridView1.GetRowCellValue(trainGridView1.FocusedRowHandle, "EndTime").ToString();
            }
        }

        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            btnRefresh.PerformClick();
        }
        private void btnSaveDB_Click(object sender, EventArgs e)
        {
            if (trainGridView1.FocusedRowHandle < 0) return;

            if (DialogResult.Yes == MessageBox.Show("将查到的信息全部存储到本地数据库，确定吗？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                DataTable dt = WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.GetTrainData(CN2PYHelper.CapitalCovert(_beginPosition), CN2PYHelper.CapitalCovert(_endPosition))));//BaseInfoCtrl.GetTrainData(CN2PYHelper.CapitalCovert(_beginPosition), CN2PYHelper.CapitalCovert(_endPosition));
                if (dt.Rows.Count > 0)//存在已有相似数据，删除...,再更新
                    foreach (DataRow dr in dt.Rows)
                        WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.DeleteTrainData(dr["TrainID"].ToString())));//BaseInfoCtrl.DeleteTrainData(dr["TrainID"].ToString());
                //将查到的数据全部存储到数据库
                for (int i = 0; i < _trains.Count; i++)
			    {
                    WcfClient.UseService((IToursDataService.IBaseInfo b) => (b.CreateTrainData(_trains[i])));//BaseInfoCtrl.CreateTrainData(_trains[i]);
                    if(i==_trains.Count-1)
                        MessageBox.Show("完成存储！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
}
